<template>
	<view class="order-confirm-page">
		<!-- 配送方式切换 -->
		<view class="delivery-method">
			<view class="delivery-item active">配送到家</view>
			<view class="delivery-item" @click="handleSelf">门店自提</view>
		</view>

		<!-- 收货地址 -->
		<view class="address-section">
			<view class="address-title">配送至</view>
			<view class="address-detail">
				<view class="address-info">
					<view class="address-name">
						{{ addressInfo.city }}{{ addressInfo.addressline2 }}{{ addressInfo.addressline1 || '请选择' }}
					</view>
					<view class="address-contact">
						<text>{{ addressInfo.name || '' }}</text>
						<text>{{ addressInfo.phone || '' }}</text>
					</view>
				</view>
				<image src="/static/修改.png" class="store-img" @click="handleUpdate" />
			</view>
			<view class="delivery-time" @click="showTimePicker">
				<view class="time-label">预计送达时间</view>
				<view class="time-value">{{ selectedDate }} {{ selectedTime }}</view>
				<image class="store-img" src="/static/大于号.png" />
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-section">
			<view class="store-info" @click="handleUpdate2">
				<image class="store-logo" src="/static/OIP-C.jpg" mode="aspectFit" />
				<text class="store-name">{{ selectedStore.storeName }}</text>
				<image class="store-img" src="/static/大于号.png" />
			</view>

			<view class="goods-list">
				<block v-for="(item, index) in goodsToShow" :key="index">
					<view class="goods-item">
						<view class="goods-image">
							<image :src="item.productImageUrl" mode="aspectFit" />
						</view>
						<view class="goods-info">
							<text class="goods-name">{{ item.name }}</text><br>
							<text class="goods-price">¥{{ item.price }}</text>
						</view>
						<view class="goods-count">x{{ item.quantity }}</view>
					</view>
				</block>
			</view>

			<view class="goods-total">
				<view class="total-label">
					<button class="show-more-btn" @click="toggleGoods">
						共{{ totalQuantity }}件
						<image v-if="!isExpanded" class="store-img" src="/static/展开.png" />
						<image v-else class="store-img" src="/static/闭合.png" />
					</button>
				</view>
			</view>
		</view>

		<!-- 费用明细 -->
		<view class="fee-section">
			<view class="fee-item">
				<text class="fee-label">商品金额</text>
				<text class="fee-value">¥{{ totalGoodsAmount.toFixed(2) }}</text>
			</view>
			<view class="fee-item">
				<text class="fee-label">配送费</text>
				<text class="fee-value">¥18.00</text>
			</view>
			<view class="fee-item coupon">
				<text class="fee-label">优惠券</text>
				<view class="coupon-info">
					<text>暂无可用</text>
					<u-icon name="arrow-right" size="24" color="#999" />
				</view>
			</view>
			<view class="fee-total">
				<text class="total-label">小计：</text>
				<text class="total-value">¥{{ totalAmount }}</text>
			</view>
		</view>

		<!-- 支付按钮 -->
		<view class="payment-section">
			<button class="payment-btn" @click="handlePay">微信支付 ¥{{ totalAmount }}</button>
		</view>

		<!-- 时间选择器 -->
		<view class="time-picker" v-if="showPicker">
			<view class="time-picker-header">
				<view class="time-picker-close" @click="closeTimePicker">×</view>
				<view class="time-picker-title">选择时间</view>
			</view>
			<view class="time-picker-content">
				<view class="date-column">
					<view class="date-item" :class="{ active: selectedDate === today }" @click="selectDate(today)">
						{{ today }} {{ weekDays[new Date().getDay()] }}
					</view>
					<view v-if="isTomorrowAvailable" class="date-item" :class="{ active: selectedDate === tomorrow }"
						@click="selectDate(tomorrow)">
						{{ tomorrow }} {{ weekDays[new Date(new Date().getTime() + 24 * 60 * 60 * 1000).getDay()] }}
					</view>
				</view>
				<view class="time-column">
					<view class="time-slot" v-for="(slot, index) in filteredTimeSlots" :key="index"
						@click="selectTimeSlot(slot)">
						<view class="time-range">{{ slot.timeRange }}</view>
						<view class="delivery-fee">{{ slot.fee }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 门店选择弹出层 -->
		<view class="store-picker" v-if="showStorePicker">
			<view class="store-picker-header">
				<view class="store-picker-close" @click="closeStorePicker">×</view>
				<view class="store-picker-title">选择门店</view>
			</view>
			<view class="store-picker-content">
				<view class="store-item" v-for="(store, index) in stores" :key="index" @click="selectStore(store)">
					<text class="store-item-name">{{ store.storeName }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		useStore
	} from 'vuex';

	const store = useStore();

	// 响应式数据
	const goodsList = ref([]);
	const showCount = ref(2);
	const isExpanded = ref(false);
	const showPicker = ref(false);
	const showStorePicker = ref(false);
	const selectedDate = ref('');
	const selectedTime = ref('');
	const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	const timeSlots = ref([{
			timeRange: '09:00-09:30',
			fee: '18元配送费'
		},
		{
			timeRange: '09:30-10:00',
			fee: '18元配送费'
		},
		{
			timeRange: '10:00-10:30',
			fee: '18元配送费'
		},
		{
			timeRange: '10:30-11:00',
			fee: '18元配送费'
		},
		{
			timeRange: '11:00-11:30',
			fee: '18元配送费'
		},
		{
			timeRange: '11:30-12:00',
			fee: '18元配送费'
		},
		{
			timeRange: '12:00-12:30',
			fee: '18元配送费'
		},
		{
			timeRange: '12:30-13:00',
			fee: '18元配送费'
		},
		{
			timeRange: '13:30-14:00',
			fee: '18元配送费'
		},
		{
			timeRange: '14:00-15:00',
			fee: '18元配送费'
		},
		{
			timeRange: '15:30-16:00',
			fee: '18元配送费'
		},
		{
			timeRange: '16:30-17:00',
			fee: '18元配送费'
		},
		{
			timeRange: '17:30-18:00',
			fee: '18元配送费'
		},
		{
			timeRange: '18:30-19:00',
			fee: '18元配送费'
		},
		{
			timeRange: '19:30-20:00',
			fee: '18元配送费'
		}
	]); // 保持原有数据
	const stores = ref([]);
	const selectedStore = ref({});
	const filteredTimeSlots = ref([]);
	const addressId = ref(null);
	const selectedStoreId = ref(null);
	const addressInfo = ref(null);
	const isTomorrowAvailable = ref(true);

	// 计算属性
	const today = computed(() => {
		const date = new Date();
		return `${date.getMonth() + 1}月${date.getDate()}日`;
	});

	const tomorrow = computed(() => {
		const date = new Date();
		date.setDate(date.getDate() + 1);
		return `${date.getMonth() + 1}月${date.getDate()}日`;
	});

	const isCurrentDate = computed(() => selectedDate.value === today.value);

	// 修改 totalQuantity 计算属性
	const totalQuantity = computed(() => goodsList.value.length);

	const totalGoodsAmount = computed(() =>
		goodsList.value.reduce((acc, item) => acc + parseFloat(item.price) * item.quantity, 0)
	);

	const totalAmount = computed(() => totalGoodsAmount.value + 18.00);

	const goodsToShow = computed(() =>
		isExpanded.value ? goodsList.value : goodsList.value.slice(0, showCount.value)
	);

	// 生命周期
	onLoad((options) => {
		
		goodsList.value = store.state.cart;
		addressInfo.value = store.state.address;
		console.log(addressInfo.value)
		addressId.value = addressInfo.value.addressid;
		
	});

	onMounted(() => {
		selectedDate.value = today.value;
		filterTimeSlots();
		setDefaultTime();
		fetchStores();
	});

	// 方法
	const fetchStores = async () => {
		const app = getApp();
		const url = app.globalData.url;
		try {
			const {
				data
			} = await uni.request({
				url: url + "USER-SERVICE/store/selectSePurchase",
				method: 'GET'
			});
			if (data) {
				stores.value = data;
				if (stores.value.length > 0) {
					selectedStore.value = stores.value[0];
					selectedStoreId.value = selectedStore.value.storeId;
				}
			}
		} catch (error) {
			console.error('获取门店数据失败:', error);
		}
	};



	const toggleGoods = () => {
		isExpanded.value = !isExpanded.value;
	};


	const handleUpdate = () => {
		uni.navigateTo({
			url: '/pages/myPage/address/address'
		});
	};

	const handleUpdate2 = () => {
		showStorePicker.value = true;
	};

	const showTimePicker = () => {
		showPicker.value = true;
	};

	const closeTimePicker = () => {
		showPicker.value = false;
	};

	const selectTimeSlot = (slot) => {
		selectedTime.value = slot.timeRange;
		closeTimePicker();
	};

	const selectDate = (date) => {
		selectedDate.value = date;
		filterTimeSlots();
		setDefaultTime();
	};

	const closeStorePicker = () => {
		showStorePicker.value = false;
	};

	const selectStore = (store) => {
		selectedStore.value = store;
		selectedStoreId.value = store.storeId;
		closeStorePicker();
	};

	const filterTimeSlots = () => {
		const now = new Date();
		const currentHour = now.getHours();
		const currentMinute = now.getMinutes();

		filteredTimeSlots.value = timeSlots.value.filter(slot => {
			const [startHour, startMinute] = slot.timeRange.split('-')[0].split(':').map(Number);
			return isCurrentDate.value ?
				startHour > currentHour || (startHour === currentHour && startMinute >= currentMinute) :
				true;
		});
	};

	const setDefaultTime = () => {
		const now = new Date();
		const currentHour = now.getHours();
		const currentMinute = now.getMinutes();

		if (isCurrentDate.value) {
			selectedTime.value = filteredTimeSlots.value.find(slot => {
				const [startHour, startMinute] = slot.timeRange.split('-')[0].split(':').map(Number);
				return startHour === currentHour && startMinute === currentMinute;
			})?.timeRange || filteredTimeSlots.value[0]?.timeRange || '';
		} else {
			selectedTime.value = timeSlots.value[0]?.timeRange || '';
		}
	};

	// 支付处理
	const handlePay = async () => {
		const salesOrderData = {
		  storeId: selectedStoreId.value, // 确保是数字
		  customerId: 1, // 确保是数字
		  amountDue: totalAmount.value, // 确保是数字
		  pendingAmount: 0, // 确保是数字
		  paymentStatus: "1", // 确保是字符串
		  actualReceivedAmount: totalAmount.value, // 实际收款金额
		  remarks: "", // 可选
		  employeeId: 1, // 确保是数字
		  deliveryType: "HOME", // 确保是字符串
		  addressId: addressId.value, // 确保是数字
		  estimatedDeliveryTime: formatDateTime(selectedDate.value, selectedTime.value), // 确保格式正确
		  orderDetails: goodsToShow.value.map(item => ({
		    productId: item.productId, // 确保是数字
		    quantity: item.quantity, // 确保是数字
		    unitPrice: item.price // 确保是数字
		  }))
		};
	  try {
	    const response = await uni.request({
	      url: 'http://localhost:15000/SALE-SERVICE/sale/createAllWX', // 替换为你的后端接口地址
	      method: 'POST',
	      data: salesOrderData,
		  header: {
		          'Content-Type': 'application/json'
		    }
	    });
	
	    if (response.data!=null) {
	      uni.showToast({
	        title: '支付成功',
	        icon: 'success',
			duration:1000
	      });
	      // 清空购物车或其他后续操作
		  store.dispatch("clearProducts");
		  uni.switchTab({
		      url: '/pages/index/index'
		    });
	    } else {
	      uni.showToast({
	        title: '支付失败',
	        icon: 'none'
	      });
	    }
	  } catch (error) {
	    console.error('支付请求失败:', error);
	    uni.showToast({
	      title: '支付请求失败',
	      icon: 'none'
	    });
	  }
	};
	// 判断当前页面是否是 home 页面
	const isHomeDelivery = ref(true);
	
	// 在导航到 home 页面时设置为 true
	const handleHome = () => {
	  uni.navigateTo({
	    url: '/pages/distribution-home/distribution-home'
	  });
	  isHomeDelivery.value = true;
	};
	
	// 在导航到自提页面时设置为 false
	const handleSelf = () => {
	  uni.navigateTo({
	    url: '/pages/distribution-self/distribution-self'
	  });
	  isHomeDelivery.value = false;
	};
	function formatDateTime(date, time) {
	  const formattedDate = `${date}T${time}:00`;
	  return formattedDate;
	}

</script>


<style scoped>
	/* 样式代码保持不变 */
	.order-confirm-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 60px;
		/* 为支付按钮留出空间 */
	}

	.payment-section {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px;
		background-color: #fff;
		z-index: 100;
	}

	.delivery-method {
		display: flex;
		background-color: #fff;
		margin-bottom: 10px;
	}

	.delivery-item {
		flex: 1;
		padding: 15px 0;
		text-align: center;
		font-size: 16px;
		color: #333;
		position: relative;
	}

	.delivery-item.active {
		color: #0096FF;
		font-weight: bold;
	}

	.delivery-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 20px;
		height: 3px;
		background-color: #0096FF;
		border-radius: 3px;
	}

	.address-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.address-title {
		font-size: 14px;
		color: #999;
		margin-bottom: 10px;
	}

	.address-detail {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 15px;
		border-bottom: 1px solid #eee;
	}

	.address-info {
		flex: 1;
	}

	.address-name {
		font-size: 16px;
		color: #333;
		margin-bottom: 5px;
	}

	.address-contact {
		display: flex;
		font-size: 14px;
		color: #666;
	}

	.address-contact text:first-child {
		margin-right: 10px;
	}

	.delivery-time {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		padding-top: 15px;
	}

	.time-label {
		font-size: 14px;
		color: #999;
	}

	.time-value {
		font-size: 14px;
		color: #0096FF;
	}

	.goods-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.store-info {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	.store-logo {
		width: 40px;
		height: 40px;
		margin-right: 10px;
	}

	.store-img {
		width: 20px;
		height: 20px;
		margin-left: 10px;
	}

	.store-name {
		font-size: 16px;
		color: #333;
	}

	.goods-list {
		margin-bottom: 10px;
	}

	.goods-item {
		display: flex;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.goods-image {
		width: 80px;
		height: 80px;
		margin-right: 15px;
	}

	.goods-info {
		flex: 1;
	}

	.goods-name {
		font-size: 14px;
		color: #333;
		margin-bottom: 5px;
	}

	.goods-price {
		font-size: 16px;
		color: #FF5722;
	}

	.goods-count {
		font-size: 14px;
		color: #999;
	}

	.goods-total {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px 0;
	}

	.total-label {
		display: flex;
		align-items: center;
		font-size: 14px;
		color: #999;
	}

	.fee-section {
		background-color: #fff;
		padding: 15px;
		margin-bottom: 10px;
	}

	.fee-item {
		display: flex;
		justify-content: space-between;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.fee-label {
		font-size: 14px;
		color: #666;
	}

	.fee-value {
		font-size: 14px;
		color: #333;
	}

	.coupon {
		border-bottom: none;
	}

	.coupon-info {
		display: flex;
		align-items: center;
		color: #0096FF;
		font-size: 14px;
	}

	.fee-total {
		display: flex;
		justify-content: flex-end;
		padding: 15px 0;
	}

	.total-label {
		font-size: 16px;
		color: #333;
	}

	.total-value {
		font-size: 18px;
		color: #FF5722;
		font-weight: bold;
		margin-left: 5px;
	}

	.payment-section {
		padding: 15px;
	}

	.payment-btn {
		width: 100%;
		height: 48px;
		background-color: #0096FF;
		color: #fff;
		border: none;
		border-radius: 24px;
		font-size: 16px;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.show-more-btn {
		padding: 0;
		margin: 0;
		background: none;
		border: none;
		color: #333;
		font-size: 14px;
	}

	.goods-image {
		width: 80px;
		height: 80px;
		margin-right: 15px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.goods-image image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	/* 时间选择器样式 */
	.time-picker {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}

	.time-picker-header {
		background-color: #fff;
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.time-picker-close {
		font-size: 20px;
		color: #999;
	}

	.time-picker-title {
		font-size: 16px;
		font-weight: bold;
	}

	.time-picker-content {
		flex: 1;
		background-color: #fff;
		display: flex;
		overflow-y: auto;
	}

	.date-column {
		width: 100px;
		border-right: 1px solid #eee;
	}

	.date-item {
		padding: 15px;
		text-align: center;
		font-size: 14px;
		color: #333;
	}

	.date-item.active {
		color: #0096FF;
		font-weight: bold;
	}

	.time-column {
		flex: 1;
		padding: 15px;
	}

	.time-slot {
		padding: 15px 0;
		border-bottom: 1px solid #eee;
	}

	.time-range {
		font-size: 16px;
		color: #333;
		margin-bottom: 5px;
	}

	.delivery-fee {
		font-size: 14px;
		color: #0096FF;
	}

	/* 门店选择器样式 */
	.store-picker {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		flex-direction: column;
	}

	.store-picker-header {
		background-color: #fff;
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.store-picker-close {
		font-size: 20px;
		color: #999;
	}

	.store-picker-title {
		font-size: 16px;
		font-weight: bold;
	}

	.store-picker-content {
		flex: 1;
		background-color: #fff;
		overflow-y: auto;
	}

	.store-item {
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.store-item-name {
		font-size: 16px;
		color: #333;
	}
</style>